const express = require('express');
const home = express.Router();
const connection = require('../mysql/index');
const moment = require('moment');

// 首页
home.get('/user', async (req, res) => {
  let arr = [];
  let notice = []
  await connection.query(`select id,Title,Createdata from news limit 6`, function (err, resulf) {
    if (err) {
      return res.render('home/index')
    }
    for (let i = 0; i < resulf.length; i++) {
      let obj = {};
      let arr1 = [];
      let arr2 = moment(resulf[i].Createdata).format('l').split('/').reverse();
      arr1[0] = arr2[0];
      arr1[1] = arr2[2];
      arr1[2] = arr2[1];
      obj['id'] = resulf[i].id;
      obj['title'] = resulf[i].Title;
      obj['date'] = arr1.join('-');
      arr.push(obj);
    }
  });
  await connection.query(`select id,Title,Createdata from notice limit 6`, function (err, resulf) {
    if (err) {
      return res.render('home/index')
    }
    for (let i = 0; i < resulf.length; i++) {
      let obj = {};
      let arr1 = [];
      let arr2 = moment(resulf[i].Createdata).format('l').split('/').reverse();
      arr1[0] = arr2[0];
      arr1[1] = arr2[2];
      arr1[2] = arr2[1];
      obj['id'] = resulf[i].id;
      obj['title'] = resulf[i].Title;
      obj['date'] = arr1.join('-');
      notice.push(obj);
    }
  })
  connection.query(`select * from links limit 6`, function (err, resulf) {
    if (err) {
      return res.render('home/index')
    }
    return res.render('home/index', {
      data1: arr,
      data2: notice,
      data3: resulf,
      msg: req.session.username || null
    });
  })



})
// 新闻详细内容
home.get('/info', (req, res) => {
  let arr1 = [];
  let arr2 = [];
  let commit = []
  const { id, name } = req.query
  connection.query(`select * from comment where Newsid=${id}`, (err, resulf) => {
    if (err) {
      commit = []
    } else {
      commit = resulf
    }
  })

  connection.query(`select * from ${name} where id = ${id}`, (err, resulf) => {
    if (err) {
      return res.render('home/404', {
        msg: '服务器错误，请重新尝试'
      })
    }
    if (resulf == []) {
      return res.render('home/404', {
        msg: '错误，请重新尝试'
      })
    }
    arr2 = moment(resulf[0].Createdata).format('l').split('/').reverse();
    arr1[0] = arr2[0];
    arr1[1] = arr2[2];
    arr1[2] = arr2[1];
    return res.render('home/info', {
      data: resulf[0],
      date: arr1.join('-'),
      msg: req.session.username || null,
      commit,
      name: name == "news" ? true : false
    })

  })

})
// 登录页面
home.get('/login', (req, res) => {
  return res.render('home/login');
});
home.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (username && password) {
    connection.query(`select * from user where username = '${username}' and password = '${password}'`, (err, resulf) => {
      if (err) {
        return res.render('home/loginError', {
          msg: '服务器出错，请重新尝试'
        })
      }
      if (resulf.length == 0) {
        return res.render('home/loginError', {
          msg: '用户或密码错误，请重新尝试'
        })
      } else {
        req.session.username = username;
        return res.redirect('/home/user')
      }
    });
  } else {
    return res.redirect('/home/login')
  }


})
home.post('/comment', (req, res) => {
  const { Content, ip, Newsid } = req.body;
  let leavedate = moment().subtract(10, 'days').calendar();
  let Author = req.session.username;
  connection.query(`insert into comment values (null,'${Author}','${Content}','${ip}',${leavedate},${Newsid})`, (err, resulf) => {
    return res.redirect('/home/user')
  })

})
home.get('/exitlogin', (req, res) => {
  req.session.destroy(function (err) {
    if (err) {
      return res.render('home/404', {
        msg: '退出登录失败，请重新尝试'
      })
    }
    return res.redirect('/home/user')
  })
})

// 注册页面
home.get('/register', (req, res) => {
  return res.render('home/register')
})
// 注册验证
home.post('/register', (req, res) => {
  const { username, password, email } = req.body;
  new Promise((resolve, reject) => {
    connection.query(`select * from user where Username = '${username}' or Email = '${email}'`, (err, resulf) => {
      if (err) {
        reject('服务器出错1')
      } else if (resulf.length !== 0) {
        reject('用户名或邮箱已存在')
      } else {
        resolve()
      }
    })
  }).then(() => {
    return new Promise((resolve, reject) => {
      connection.query(`insert into user values (null ,'${username}','${password}','${email}','in') `, (err, resulf) => {
        if (err) {
          reject('服务器出错')
        } else {
          resolve(true)
        }
      })

    })
  }).then((value) => {
    res.render('home/loginError',{
      msg: '注册完成'
    })
  }).catch((err) => {
    res.render('home/registerError', {
      msg: err
    })
  })

})
module.exports = home